package com.example.mq.rocketmq.consumer;

import com.alibaba.fastjson.JSONArray;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 推送模式的消费者
 *
 * @author luowj12
 * @since 2021/4/26 9:32
 */
public class MQPushConsumer {

    /**
     * 顺序消息消费，带事务方式（应用可控制Offset什么时候提交）
     */
    public static void main(String[] args) throws Exception {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("sync_store_group");
        consumer.setNamesrvAddr("10.58.218.163:9876");
        /**
         * 设置Consumer第一次启动是从队列头部开始消费还是队列尾部开始消费<br>
         * 如果非第一次启动，那么按照上次消费的位置继续消费
         */
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        //订阅指定得topic和tag
        consumer.subscribe("secp_smc_topic", "tag_sync_store");
        consumer.registerMessageListener(new MessageListenerOrderly() {
            Random random = new Random();
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
                context.setAutoCommit(true);
                System.out.println(msgs.size());
                for (MessageExt msg : msgs) {
                    //获取信息体
                    System.out.println(new String(msg.getBody()));
                    //转成实体
                    /*JSONArray objects = JSONUtil.parseArray(new String(msg.getBody()));
                    List<StoreDemo> storeSyncVOS = JSONUtil.toList(objects, StoreDemo.class);
                    System.out.println("==============>" + storeSyncVOS);*/
                }
                try {
                    //模拟业务逻辑处理中...
                    TimeUnit.SECONDS.sleep(random.nextInt(10));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });
        consumer.start();
        System.out.println("Consumer Started.");
    }

}
